﻿using System;
using System.Reflection;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

namespace RDPAddins.Core
{
    class EntryPoint
    {
        static readonly string AssemblyName = "RDPAddins.exe";
        static readonly string AssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        static readonly string AssemblyFullPath = Path.Combine(AssemblyPath, AssemblyName);
        static readonly string ConfigFileFullPath = string.Format("{0}.config",  AssemblyFullPath);

        [ExportDll("VirtualChannelEntry", CallingConvention.StdCall)]
        public static bool VirtualChannelEntry(IntPtr entry)
        {
            try
            {
                ManualResetEvent wait = new ManualResetEvent(false);
                AppDomain app = null;
                var thread = new Thread(() =>
                {

                    app = AppDomain.CreateDomain(AssemblyName, null,
                        new AppDomainSetup()
                        {
                            ApplicationBase = AssemblyName,
                            ApplicationName = AssemblyPath,
                            ConfigurationFile = ConfigFileFullPath
                        });
                    app.SetData("entry", entry);
                    app.SetData("event", wait);
                    app.ExecuteAssembly(AssemblyFullPath);
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                wait.WaitOne();
                return (bool)app.GetData("ret");
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}